package com.topvision.utils.glass;


import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.report.ReceivedsResult;
import org.apache.commons.lang.StringUtils;
import cn.jpush.api.JPushClient;

import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.PushPayload.Builder;
import cn.jpush.api.push.model.audience.Audience;

import java.util.HashMap;
import java.util.Map;


public class JpushUtil {

    @SuppressWarnings("deprecation")
    static JPushClient jpushClient = new JPushClient("36c507742ca440793ca43536", "db1f3037515df21a53a976a4", 3);
    public static final String PUSHLAUNCHERAPPINFO = "pushLauncherAppinfo";
    public static final String PUSH_TEXT = "pushText";

    /**
     * 通过tags推送Launcher桌面App
     *
     * @param tags
     * @param msgContent
     * @param apps
     * @return
     */
    public static boolean sendByTags(String[] tags, String msgContent, String apps) {
        PushPayload payload = BuildTagPushPayload(tags, msgContent, apps);
        try {
            PushResult result = jpushClient.sendPush(payload);
            return result.isResultOK();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * 构建标签推送对象
     *
     * @return
     */
    public static PushPayload BuildTagPushPayload(String[] tags, String msg, String apps) {
        return PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.tag(tags))
                .setMessage(Message.newBuilder().setMsgContent(msg).addExtra("apps", apps).build()).build();

    }


    public static Map<String, Object> customNotification(com.topvision.model.glass.Message message) {
        String recipientType = message.getRecipienttype();
        PushPayload pushPayload = null;
        Map<String, Object> resultMap = new HashMap<>();
        if ("broadcast".equals(recipientType)) {
            pushPayload = customNotificationAll(message);
        } else if ("tags".equals(recipientType)) {
            pushPayload = customNotificationTags(message);
        } else if ("alias".equals(recipientType)) {
            pushPayload = customNotificationAlias(message);
        }
        try {
            PushResult pushResult = null;
            try {
                pushResult = jpushClient.sendPush(pushPayload);
                resultMap.put("success", pushResult.isResultOK());
                resultMap.put("msgId", pushResult.msg_id);
            } catch (APIConnectionException e) {
                e.printStackTrace();
                resultMap.put("success", false);
                resultMap.put("info", e.getMessage());
                resultMap.put("code", 2);
            }
        } catch (APIRequestException e) {
            resultMap.put("success", false);
            resultMap.put("info", e.getErrorMessage());
            resultMap.put("code", e.getErrorCode());
        }

        return resultMap;

    }

    private static PushPayload customNotificationAlias(com.topvision.model.glass.Message message) {
        Builder builder = null;
        PushPayload pushPayload = null;
        if (!StringUtils.isEmpty(message.getDevicealias())) {
            Message.Builder msgBuilder = buildExtra(message);
            String[] aliasArray = message.getDevicealias().split(",");
            builder = PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.alias(aliasArray))
                    .setMessage(msgBuilder.build());

            pushPayload = builder.build();
        }
        return pushPayload;

    }

    private static PushPayload customNotificationTags(com.topvision.model.glass.Message message) {
        Builder builder = null;
        PushPayload pushPayload = null;
        if (!StringUtils.isEmpty(message.getDevicetags())) {
            Message.Builder msgBuilder = buildExtra(message);
            String[] tagsArray = message.getDevicetags().split(",");
            builder = PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.tag(tagsArray))
                    .setMessage(msgBuilder.build());

            pushPayload = builder.build();
        }
        return pushPayload;
    }

    /**
     * 全平台推送
     *
     * @param message
     */
    private static PushPayload customNotificationAll(com.topvision.model.glass.Message message) {
        // 创建msgBuilder对象以及封装一些参数
        Message.Builder msgBuilder = buildExtra(message);
        Builder builder = PushPayload.newBuilder().setPlatform(Platform.android()).setAudience(Audience.all())
                .setMessage(msgBuilder.build());
        PushPayload pushPayload = builder.build();
        return pushPayload;
    }

    // 构建传递的参数
    private static Message.Builder buildExtra(
            com.topvision.model.glass.Message message) {
        Message.Builder msgBuilder = Message.newBuilder().setMsgContent(message.getAlert());
        String customKeys = message.getCustomkeys();
        String[] customKeysArray = null;
        if (!StringUtils.isEmpty(customKeys)) {
            customKeys = StringUtils.trim(customKeys);
            // 去除最前面[ 和最后的]
            customKeys = customKeys.substring(1, customKeys.length() - 1);
            customKeysArray = customKeys.split(",");

        }

        for (int i = 0; customKeysArray != null && i < customKeysArray.length; i++) {
            // 把地址最後一個
            String url = replaceShuangyinhao(customKeysArray[i]);
            if (url.contains("/")) {
                String keyName = url.substring(url.lastIndexOf("/") + 1, url.length());
                msgBuilder.addExtra(keyName, url);
            } else if ("deleteApp".equals(message.getAlert())) {
                // 将数据传参过去
                // TODO 这边把key 也设为了url,为的是添加多个addExtra。不重复
                msgBuilder.addExtra("app" + i, url);
            } else if (PUSH_TEXT.equals(message.getAlert())) {
                msgBuilder.addExtra("text" + i, url);
            }

        }
        return msgBuilder;
    }

    /**
     * 去除双引号
     */
    public static String replaceShuangyinhao(String str) {
        return str.replaceAll("\"", "");
    }


    public static String getReportReceiveds(String msgId) {
        ReceivedsResult result = null;
        try {
            result = jpushClient.getReportReceiveds(msgId);

        } catch (APIConnectionException e) {
            // Connection error, should retry later

        } catch (APIRequestException e) {
            // Should review the error, and fix the request

        }
        return "aa";
    }

}
